<?php
namespace app\admin\controller;

use app\common\model\Article as ArticleModel;
use app\common\model\Category as CategoryModel;
use app\common\controller\AdminBase;
use app\common\model\ArticleClass as ArticleClassModel;
use think\cache\driver\Redis;
use think\Db;

/**
 * 文章管理
 * Class Article
 * @package app\admin\controller
 */
class Article extends AdminBase
{
    protected $article_model;
    protected $category_model;


    protected function _initialize()
    {
        parent::_initialize();
        $this->article_model  = new ArticleModel();
        $this->category_model = new CategoryModel();

        $category_level_list = $this->category_model->getLevelList();
        $this->assign('category_level_list', $category_level_list);
    }

    /**
     * 文章管理
     * @param int    $cid     分类ID
     * @param string $keyword 关键词
     * @param int    $page
     * @return mixed
     */
    public function index($cid = 0,$aid = 0, $is_recommend = 0, $status = 0, $keyword = '', $page = 1)
    {
        $map   = [];
        $field = 'id,title,cid,reading,status,publish_time,sort,is_recommend,recommend,thumb';
        if ($cid > 0) {
            $category_children_ids = $this->category_model->where(['path' => ['like', "%,{$cid},%"]])->column('id');
            $category_children_ids = (!empty($category_children_ids) && is_array($category_children_ids)) ? implode(',', $category_children_ids) . ',' . $cid : $cid;
            $map['cid']            = ['IN', $category_children_ids];
        }

        if ($aid > 0) {
            //文章种类
            $map['article_class']            = $aid;
        }


            //审核状态
        if($status == 1){
            $map['status'] = 0;
        }else if ($status == 2){
            $map['status'] =1;
        }



        if($is_recommend ==1){
            $map['recommend'] = ['<>',10000];
        }else if ($is_recommend == 2){
            $map['recommend'] = 10000;
        }

        if (!empty($keyword)) {
            $map['title'] = ['like', "%{$keyword}%"];
        }
        if(session('admin_name') != 'admin'){
            $map['author'] = session('admin_name');
        }

        $article_list  = Db::table('lsj_article')
        ->field($field)->where($map)->order(['recommend' => 'ASC','reading' => 'DESC','create_time' => 'DESC'])->paginate(15, false, ['page' => $page]);

        return $this->fetch('index', ['recommend'=>$is_recommend,'status'=>$status,'article_list' => $article_list,'cid' => $cid, 'aid' => $aid,  'keyword' => $keyword]);
    }

    /**
     * 添加文章
     * @return mixed
     */
    public function add()
    {
        return $this->fetch();
    }

    /**
     * 保存文章
     */
    public function save()
    {
        if ($this->request->isPost()) {
            $data            = $this->request->param();
            $validate_result = $this->validate($data, 'Article');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                if(isset($data['photos']) && is_array($data['photos'])){
                    $data['photos'] = json_encode($data['photos']);
                }

                if ($this->article_model->allowField(true)->save($data)) {
                    $this->success('保存成功');
                } else {
                    $this->error('保存失败');
                }
            }
        }
    }

    /**
     * 编辑文章
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        $article = Db::table('lsj_article')
            ->where("id={$id}")
            ->find();

        if(!empty($article['photos'])){
            $photos_array = json_decode($article['photos']);
            $article['photos'] = $photos_array;
        }

        return $this->fetch('edit', ['article' => $article]);
    }

    /**
     * 更新文章
     * @param $id
     */
    public function update($id)
    {
        if ($this->request->isPost()) {
            $data            = $this->request->param();
            if(isset($data['photos']) && is_array($data['photos'])){
                $data['photos'] = json_encode($data['photos']);
            }
            /*$validate_result = $this->validate($data, 'Article');
            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {*/
                if ($this->article_model->allowField(true)->save($data, $id) !== false) {
                    $this->success('更新成功');
                } else {
                    $this->error('更新失败');
                }
            //}
        }
    }

    /**
     * 删除文章
     * @param int   $id
     * @param array $ids
     */
    public function delete($id = 0)
    {
        if ($id) {
            if ($this->article_model->destroy($id)) {
                $this->success('删除成功');
            } else {
                $this->error('删除失败');
            }

        } else {
            $this->error('请选择需要删除的文章');
        }
    }
	
	/**
     * 多选删除文章
     * @param int   $id
     * @param array $ids
     */
    public function moreDelete($ids = [])
    {
        if ($ids) {
            if ($this->article_model->destroy($ids)) {
                $this->success('删除成功');
            } else {
                $this->error('删除失败');
            }
        } else {
            $this->error('请选择需要删除的文章');
        }
    }

    /**
     * 文章审核状态切换
     * @param array  $ids
     * @param string $type 操作类型
     */
    public function toggle($ids = [], $type = '')
    {
        $data   = [];
        $status = $type == 'audit' ? 1 : 0;

        if (!empty($ids)) {
            foreach ($ids as $value) {
                $data[] = ['id' => $value, 'status' => $status];
            }
            if ($this->article_model->saveAll($data)) {
                $this->success('操作成功');
            } else {
                $this->error('操作失败');
            }
        } else {
            $this->error('请选择需要操作的文章');
        }
    }

    /**
     * 文章分享状态该表
     */
    public function shareStatus($ids = [], $type = '')
    {
        $data   = [];
        $status = $type == 'allow' ? 1 : 0;

        if (!empty($ids)) {
            foreach ($ids as $value) {
                $data[] = ['id' => $value, 'is_share' => $status];
            }
            if ($this->article_model->saveAll($data)) {
                $this->success('操作成功');
            } else {
                $this->error('操作失败');
            }
        } else {
            $this->error('请选择需要操作的文章');
        }
    }
	
	/**
	* 随便看看
	**/
	public function recommend($ids = [], $type = '')
    {
        $data   = [];
        $status = $type == 'allow' ? 1 : 0;

        if (!empty($ids)) {
            foreach ($ids as $value) {
                $data[] = ['id' => $value, 'is_recommend' => $status];
            }
            if ($this->article_model->saveAll($data)) {
                $this->success('操作成功');
            } else {
                $this->error('操作失败');
            }
        } else {
            $this->error('请选择需要操作的文章');
        }
    }

    /**
     * 推荐作品
     */
    public function recommendWorks($ids = [], $type = '')
    {
        $data   = [];
        $status = $type == 'allow' ? 1 : 10000;
        $num = 10000;

        $in_ids = implode($ids,",");

        $is_rec = Db::table('lsj_article')
            ->where("recommend<>10000 and id in ({$in_ids})")
            ->count();

        if($status == 1){

            if($is_rec){
                $this->error('请勿重复推荐!');
            }
            //推荐
            $last_recommend = Db::table('lsj_article')
                ->where(['recommend'=>['<>',10000]])
                ->field('recommend')
                ->order(['recommend'=>'DESC'])
                ->limit(1,1)
                ->find();

            if($last_recommend){
                $num = $last_recommend['recommend'];
            }else{
                $num = 0;
            }
        }


        if (!empty($ids)) {
            foreach ($ids as $key=>$value) {
                if($status == 1){
                    $data[] = ['id' => $value, 'recommend' => $key+$num+1];
                }else{
                    $data[] = ['id' => $value, 'recommend' => 10000];
                    $article = Db::table('lsj_article')->where('id',$value)->field('recommend')->find();

                    if($article['recommend']!=10000){
                        Db::table('lsj_article')
                            ->where("recommend<>10000 and recommend>{$article['recommend']}")
                            ->setDec('recommend');
                    }
                }
            }

            if ($this->article_model->saveAll($data)) {
                $this->success('操作成功');
            } else {
                $this->error('操作失败');
            }
        } else {
            $this->error('请选择需要操作的文章');
        }
    }
    /**
     * 人工排序
     */
    public function sortWorks($sort = 1,$article_id = 0)
    {

        if($sort<=0){
            $sort = 1;
        }
        //获得当前的排名
        $before_rank = Db::table('lsj_article')->where(['id'=>$article_id,'recommend'=>['<>',10000]])->field('recommend')->find();

        if($before_rank){


            $rank_exits = Db::table('lsj_article')->where("recommend ={$sort} and recommend !=10000")->field('recommend')->find();

            if($rank_exits){
                //判断排名是否存在
                if($before_rank['recommend']<$sort){
                    //减一
                    Db::table('lsj_article')->where("recommend > {$before_rank['recommend']} and recommend<= $sort and recommend!=10000")->setDec('recommend');
                }else{
                    //加一
                    Db::table('lsj_article')->where("recommend >= $sort and recommend<{$before_rank['recommend']}  and recommend!=10000")->setInc('recommend');
                }
                Db::table('lsj_article')->where('id',$article_id)->update(['recommend'=>$sort]);
            }else{

                $last_recommend = Db::table('lsj_article')
                    ->where(['recommend'=>['<>',10000]])
                    ->field('recommend')
                    ->order(['recommend'=>'DESC'])
                    ->limit(1,1)
                    ->find();

                if($sort>$last_recommend['recommend']){
                    //输入的为大于最后排名的数
                    Db::table('lsj_article')->where("recommend > {$before_rank['recommend']} and recommend<= $sort and recommend!=10000")->setDec('recommend');
                    Db::table('lsj_article')->where('id',$article_id)->update(['recommend'=>$last_recommend['recommend']]);
                }else{
                    //输入的为排名区间内不存在的数
                    Db::table('lsj_article')->where('id',$article_id)->update(['recommend'=>$sort]);
                }

            }
        }
    }

    /**
     *
     */
    public function sort()
    {
        return $this->fetch('sort');
    }
}